﻿#include "mainwindow.h"
#include "appcommon.h"
#include "ui_mainwindow.h"
#include <QDateTime>
#include <QSystemTrayIcon>
#include <QTimer>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent), ui(new Ui::MainWindow) {
    ui->setupUi(this);

    setWindowTitle("VPN 连接信息");

    // 创建定时器
    m_timer = new QTimer(this);
    connect(m_timer, &QTimer::timeout, this, &MainWindow::updateConnectionDuration);

    m_needExit = false;
}

MainWindow::~MainWindow() {
    delete ui;
}

void MainWindow::closeEvent(QCloseEvent *event) {
    if(m_needExit){
        return;
    }
    event->ignore();
    if (QSystemTrayIcon::isSystemTrayAvailable()) {
        hide();
    }
}

void MainWindow::setVpnInfo(QString serverAddress, QString hubName, QString username, QString vpnIP, QDateTime connectTime) {
    ui->txtHostIP->setText(serverAddress);
    ui->txtHubName->setText(hubName);
    ui->txtUserName->setText(username);
    ui->txtVPNIP->setText(vpnIP);
    m_connectTime = connectTime;
    ui->txtOnlineState->setText("在线");
    // 立即更新一次显示
    updateConnectionDuration();
    m_timer->start(1000); // 每秒触发一次
}

void MainWindow::updateConnectionDuration() {
    if (m_connectTime.isValid()) {
        qint64 seconds = m_connectTime.secsTo(QDateTime::currentDateTime());
        ui->txtOnlineTime->setText(AppCommon::formatSecondTime(seconds));
    }
}

void MainWindow::setNeedExit(bool needExit)
{
    m_needExit = needExit;
}

void MainWindow::on_btnLogout_clicked() {
    emit needLogout();
    m_timer->stop();
    ui->txtOnlineState->setText("离线");
}
